#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

/*

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                      void *(*start_routine) (void *), void *arg);


int pthread_join(pthread_t thread, void **retval);
void pthread_exit(void *retval);

// pthread_attr_t attr;
// int pthread_attr_init(pthread_attr_t *attr);
// int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
// int pthread_attr_destroy(pthread_attr_t *attr);


// int pthread_detach(pthread_t thread);

// pthread_t pthread_self(void);

int pthread_cancel(pthread_t thread);
int pthread_setcancelstate(int state, int *oldstate);
int pthread_setcanceltype(int type, int *oldtype);
*/

int pthread_status = 11;

void *start_routine(void *arg)
{
    int cnt = 0;
    // 设置子线程响应取消请求的类型是 PTHREAD_CANCEL_DEFERRED（默认） 延迟到   取消点函数
    // pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    printf("子线程 %d\n", *((int *)arg));
    while (1)
    {
        // printf("world\n");
        // sleep(1);
    }
    // 如果设置的是PTHREAD_CANCEL_DEFERRED 没有取消点函数 一直取消不了
}

int main()
{
    int count = 1;

    printf("main 单个进程 的主线程\n");

    // 创建一个线程
    pthread_t thread;
    int res_create = pthread_create(&thread, NULL, start_routine, &count);
    printf("res_create=%d\n", res_create);

    sleep(5);
    // 发起取消线程请求
    int ret_cancel = pthread_cancel(thread);
    printf("ret_cancel=%d\n", ret_cancel);

    // 等待子线程退出(阻塞的)
    int ret_join = pthread_join(thread, NULL);
    printf("ret_join=%d\n", ret_join);

    return 0;
}
